<?php

class CategoryImport extends ImportBase
{
	private $category_table = 'categories';
	private $category_description_table = 'categories_description';
	private $api;
	
	protected $db;
	
	public function __construct()
	{
		global $config;
		//echo "{$config['db_host']},{$config['db_user']},{$config['db_pass']},{$config['db_name']}";
		$this->set_s_db( $config['db_host'],$config['db_user'],$config['db_pass'],$config['db_name'] );
		$this->api = Mage::getModel('catalog/category_api');;
		$this->db = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
		
		parent::__construct();
	}
	
	function start_transation()
	{
		global $config;
		$this->db->query( "UPDATE `eav_attribute` SET `is_required` = '0' WHERE `attribute_id` ={$config['available_sort_by_id']} LIMIT 1 " );
		$this->db->query( "UPDATE `eav_attribute` SET `is_required` = '0' WHERE `attribute_id` ={$config['default_sort_by_id']} LIMIT 1 " );
	}
	
	function transation_commit()
	{
		global $config;
		$this->import_counter++;
		if( $this->import_counter > $this->import_num ){
			$this->db->query( "UPDATE `eav_attribute` SET `is_required` = '1' WHERE `attribute_id` ={$config['available_sort_by_id']} LIMIT 1 " );
			$this->db->query( "UPDATE `eav_attribute` SET `is_required` = '1' WHERE `attribute_id` ={$config['default_sort_by_id']} LIMIT 1 " );
			$this->redirect( Mage::getBaseUrl( 'web' ) . "scripts_import/import.php?time=" . time() );
			exit();
		}
	}
	
	function run()
	{
		global $config;
		$category_index_array = array();
		$this->find_child_category( $category_index_array,0 );
		$this->start_transation();
		
		if( count( $category_index_array ) ){
			echo 'try to import total of categories :'.count( $category_index_array ).'<br />';
			foreach( $category_index_array as $_category_index ){
				
				$this->import_category( $_category_index['id_category'],$_category_index['parent_id'] );
				
			}
		}
		
		//if get here.
		$this->db->query( "UPDATE `eav_attribute` SET `is_required` = '1' WHERE `attribute_id` ={$config['available_sort_by_id']} LIMIT 1 " );
		$this->db->query( "UPDATE `eav_attribute` SET `is_required` = '1' WHERE `attribute_id` ={$config['default_sort_by_id']} LIMIT 1 " );

		
	}
	
	public function import_category( $id_category,$id_parent )
	{		
		global $config;
		
		if( $id_category > 0 ){
			
			//check if already import
			$categiry_exist = $this->read_log( array( 'org_category_id' => $id_category ) );
			
			if( !$categiry_exist ){		
				
				if( $id_parent > 0 ){ // check the real parent id.
					$parent_id_log = $this->read_log( array( 'org_category_id' => $id_parent ) );
					if( !empty( $parent_id_log[0] ) ) $id_parent = $parent_id_log[0]['category_id'];
					else $id_parent = 0;
				}
				
				!$id_parent && $id_parent = $config['root_cattegory'];	
				
				$category_array = $this->read_category( $id_category );
				
				
				$categry_id = $this->api->create($id_parent, array("name"=>$category_array['default']['categories_name'],
																"description"=>$category_array['default']['categories_description'],
																'meta_title' => $category_array['default']['categories_head_title_tag'],
																"meta_keywords" => $category_array['default']['categories_head_keywords_tag'],
																"meta_description" => $category_array['default']['categories_head_desc_tag'],																
																	"is_active"=>$category_array['default']['categories_status'],));
				
				foreach( $category_array as $key => $_category ){
					if( is_numeric( $key ) ){						
						$this->api->update($categry_id, array( "name"=>$_category['categories_name'],
																"description"=>$_category['categories_description'],
																'meta_title' => $_category['categories_head_title_tag'],
																"meta_keywords" => $_category['categories_head_keywords_tag'],
																"meta_description" => $_category['categories_head_desc_tag'],
																 ),  $key );
					}
				}
				
				if( $config['enable_category_image'] && isset( $category_array['default']['categories_image'] ) ){
					$this->import_image( $category_array['default']['categories_image'],$categry_id );
				}
				
				//log the category
				$this->log( array( 'org_category_id'=>$id_category,'category_id'=>$categry_id ) );
				$this->transation_commit();
				
			}
			
			
		}
	}
	
	/*return category with store view as key*/
	protected function read_category( $id_category )
	{
		global $config;
		$category_data = array();
		
		$store_views = $this->allStoreViews();
		
		$query = "select * from `{$this->category_description_table}` d join `{$this->category_table}` c on d.categories_id=c.categories_id where c.categories_id = '{$id_category}'";
		$this->s_db->query( $query );
		$categories = $this->s_db->af();
		
		$lang2storeviews = array_flip( $config['store_views'] );
		foreach( $categories as $_category ){
			if( isset( $lang2storeviews[ $_category['language_id'] ] ) && $_category['language_id'] != $config['default_lang'] ){
				$category_data[ $this->getStoreIdByCode( $lang2storeviews[ $_category['language_id'] ] ) ] = $_category;
			}else if( $_category['language_id'] == $config['default_lang'] ){
				$category_data[ 'default' ] = $_category;
			}
		}
		
		return $category_data;
	}
	
	public function find_child_category( &$categories,$id_category=0,$deep='' )
	{		
		static $level;
		
		$child_categories = array();		
		
		$condition = array();
		$query = "select * from {$this->category_table} where parent_id = '{$id_category}' order by sort_order";
		$this->s_db->query( $query );
		$child_category = $this->s_db->af();
		
		if( !empty( $child_category ) ){
			$level++;
			if( !empty( $deep ) ){
				
				if( $level <= $deep ){
					foreach( $child_category as $index => $this_child_category ){
						$category['id_category'] = $this_child_category['categories_id'];						
						$category['parent_id'] = $this_child_category['parent_id'];						
						$category['level'] = $level;
						$child_categories[] =	$category;	
						$this->find_child_category( $child_categories,$this_child_category['categories_id'],$deep );		
					}
				}	
				
			}else{
				foreach( $child_category as $index => $this_child_category ){
					
					$category['id_category'] = $this_child_category['categories_id'];						
					$category['parent_id'] = $this_child_category['parent_id'];						
					$category['level'] = $level;
					$child_categories[] =	$category;	
					$this->find_child_category( $child_categories,$this_child_category['categories_id'],$deep );		
				}			
			}
			$level--;
		}
		$categories = array_merge( $categories,$child_categories );		
		
		
	}
	
	function import_image( $file,$categry_id )
	{
		global $config;
		
		if( file_exists( $config['category_images_base_folder_os'] . $file ) ){
			
			$file_name = basename( $file );
			
			if( file_exists( $config['category_images_base_folder_magento'] . $file_name ) ){
				$file_name = time().$file_name;
				
			}
			
			if( copy( $config['category_images_base_folder_os'] . $file,$config['category_images_base_folder_magento'] . $file_name ) ){	
				echo "insert into catalog_category_entity_varchar (entity_type_id,attribute_id,store_id,entity_id,value) values ('{$config['category_entity_type_id']}','{$config['category_image_attribute_id']}','0','{$categry_id}','{$file_name}')<br />";		
				$this->db->query ( "insert into catalog_category_entity_varchar (entity_type_id,attribute_id,store_id,entity_id,value) values ('{$config['category_entity_type_id']}','{$config['category_image_attribute_id']}','0','{$categry_id}','{$file_name}')" );
				
			}
		}
	}
}